<template>
  <a-select
    v-model:value="selectValue"
    class="min-w-[160px]"
    :options="options"
    placeholder="请选择"
    show-search
    :filter-option="false"
    :allow-clear="allowClear"
    @search="onSearch"
    @change="onChange"
    @focus="onFocus"
  >
    <template v-if="loading" #notFoundContent>
      <a-spin size="small" />
    </template>
  </a-select>
</template>

<script setup>
/**
 * @name:选择病区
 */
import { ref, onMounted, watchEffect } from 'vue'
import { debounce } from 'lodash-es'
import { post } from '@/utils/request'

const props = defineProps({
  value: {
    type: String,
    default: null
  },
  trigger: {
    desc: '请求数据时机init:初始化/focus:聚焦',
    type: String,
    default: 'init'
  },
  allowClear: {
    type: Boolean,
    default: false
  }
})
const selectValue = ref(null)
const loading = ref(false)

watchEffect(() => {
  selectValue.value = props.value || null
})
const options = ref([])
const onSearch = debounce((searchKey) => {
  getData(searchKey)
}, 400)
const getData = async (searchKey = '') => {
  loading.value = true
  const { data } = await post('/common/masterData/getAreaInfoList', {
    name: searchKey,
    pageNum: 1,
    pageSize: 10
  })
  options.value = data.map((item) => {
    return {
      label: `${item.province}/${item.city}/${item.county}`,
      value: `${item.province}/${item.city}/${item.county}`,
      data: item
    }
  })
  loading.value = false
}

const emit = defineEmits(['update:value', 'change'])

const onChange = (value, option) => {
  selectValue.value = value
  emit('update:value', value)
  emit('change', value, option)
}
const onFocus = () => {
  props.trigger === 'focus' && getData()
}
onMounted(() => {
  props.trigger === 'init' && getData()
})
</script>
